package com.liuyjy.utils.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;
import java.io.StringReader;
import java.io.StringWriter;

/**
 * @Author liuyjy
 * @Date 2024/12/27 9:33
 * @Description: xml解析工具类
 **/
@Slf4j
public class XmlToObjUtil {

    /**
     * 将 Java 对象转换为 XML
     *
     * @param obj 要转换的 Java 对象
     * @return XML 字符串
     */
    public static <T> String objToXml(T obj) {
        if (null == obj) {
            log.error("将 Java 对象转换为 XML:参数为空");
            return null;
        }
        // 将 Java 对象转换为 XML
        try {
            JAXBContext context = JAXBContext.newInstance(obj.getClass());
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");

            StringWriter writer = new StringWriter();
            marshaller.marshal(obj, writer);
            return writer.toString();

        } catch (JAXBException e) {
            //e.printStackTrace();
            log.error("xmlToObj error", e);
        }
        return null;
    }

    /**
     * 将 XML 转换为 Java 对象
     *
     * @param xmlString XML 字符串
     * @param clazz     Java 对象的类
     * @return Java 对象
     */
    public static <T> T xmlToObj(String xmlString, Class<T> clazz) {
        if (StringUtils.isBlank(xmlString)) {
            log.error("将 XML 转换为 Java 对象:参数为空！");
            return null;
        }
        // 将 Java 对象转换为 XML
        JAXBContext jaxbContext = null;
        try {
            jaxbContext = JAXBContext.newInstance(clazz);
        } catch (JAXBException e) {
            throw new RuntimeException(e);
        }
        Unmarshaller unmarshaller = null;
        try {
            unmarshaller = jaxbContext.createUnmarshaller();
        } catch (JAXBException e) {
            throw new RuntimeException(e);
        }
        StreamSource streamSource = new StreamSource(new StringReader(xmlString));
        try {
            @SuppressWarnings("unchecked")
            T unmarshal = (T) unmarshaller.unmarshal(streamSource);
            return unmarshal;
        } catch (JAXBException e) {
            log.error("xmlToObj error", e);
            //throw new RuntimeException(e);
        }
        return null;
    }


}
